package org.crud4j.wicket.markup.html.edit;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.crud4j.core.BeforeCreateException;
import org.crud4j.core.BeforeUpdateException;
import org.crud4j.core.CrudBean;
import org.crud4j.core.CrudField;
import org.crud4j.core.CrudService;
import org.crud4j.core.IdInUseException;
import org.crud4j.core.RemoveMarkException;
import org.crud4j.wicket.CrudServiceInjectable;
import org.crud4j.wicket.markup.html.browse.BrowsePanel;

public class EditPanel extends Panel {

	private static final long serialVersionUID = 1L;

	private class CreateForm extends Form implements CrudServiceInjectable {

		private static final long serialVersionUID = 1L;

		private transient CrudService crudService;

		public CreateForm(String id, IModel model) {
			super(id, model);
			CrudBean bean = ((EditModel) model.getObject()).getBean();
			
			// exclude hidden fields && generated values
			List<CrudField> fields = new ArrayList<CrudField>();
			for (CrudField f : bean.getFields()) {
				if (!f.getDef().isHidden()) {
					fields.add(f);
				}
			}

			// add editors to the form
			EditFormList list = new EditFormList("fields", fields);
			add(list);

			// add cancel button
			Button cancel = new Button("cancel") {

				@Override
				public void onSubmit() {
					gotoBrowsePanel();
				}

			};
			cancel.setDefaultFormProcessing(false);
			add(cancel);
		}

		@Override
		protected void onSubmit() {
			EditModel model = (EditModel) this.getModel().getObject();
			CrudBean bean = model.getBean();
			try {
				model.setBean(this.crudService.persist(bean));				
				this.gotoBrowsePanel();
			} catch (RemoveMarkException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IdInUseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (BeforeCreateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (BeforeUpdateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		private void gotoBrowsePanel() {
			EditModel model = (EditModel) this.getModel().getObject();
			EditPanel.this.replaceWith(new BrowsePanel(EditPanel.this.getId(),
					model.getBrowseModel()));
		}

		public void setCrudService(CrudService crudService) {
			this.crudService = crudService;
		}

	}

	public EditPanel(String id, IModel model) {
		super(id, model);

		// feedback
		FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback);

		CreateForm form = new CreateForm("form", model);
		add(form);
	}

}
